<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        :model="formData"
        ref="ruleFormRef"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="组名" prop="groupName">
          <el-input v-model="formData.groupName" style="width: 85%" />
        </el-form-item>
        <el-form-item label="是否启用" prop="isUsed">
          <el-radio-group v-model="formData.isUsed">
            <el-radio label="1">启用</el-radio>
            <el-radio label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限属性" prop="permissionProperties">
          <el-radio-group v-model="formData.permissionProperties">
            <el-radio label="1">公开组</el-radio>
            <el-radio label="2">私有组</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="公开范围">
          <!-- 后换为部门组件 -->
          <el-input v-model="formData.publicScope" style="width: 85%" />
        </el-form-item>
        <el-form-item label="管理员">
          <!-- 后换为部门组件 -->
          <el-input v-model="formData.administrators" style="width: 85%" />
        </el-form-item>

        <el-table
          :data="formData.tableData"
          :key="teamTableKey"
          :header-cell-style="{
            background: '#eff2fb',
            color: 'var(--el-text-color-primary)'
          }"
        >
          <el-table-column
            v-for="(item, index) in tableColums"
            :key="index"
            :width="item.width"
          >
            <template #header>
              <span>{{ item.label }}</span>
              <div @click="addPerson" style="cursor: pointer">
                <IconifyIconOffline :icon="Plus" v-if="item.type === 'icon'" />
              </div>
            </template>
            <template #default="{ row, $index }">
              <el-form-item
                label-width="0"
                :prop="`tableData.${$index}` + `.${item.prop}`"
                :rules="rules[item.prop]"
              >
                <!-- 后换为换人组件 -->
                <el-input
                  v-if="item.type === 'people'"
                  v-model="row.userInfo"
                />
                <!-- 后换为部门组件 -->
                <el-input
                  v-if="item.type === 'department'"
                  v-model="row.controlScope"
                />
                <el-button
                  @click="deletePerson($index)"
                  v-if="item.type === 'operate'"
                  link
                  type="primary"
                  >删除</el-button
                >
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item
          label-width="0"
          style="margin-top: 20px; margin-left: 200px"
        >
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="onSubmit(ruleFormRef)"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import Plus from "@iconify-icons/ep/plus";

const props = defineProps(["title"]);
const dialogVisible = ref(false);

const handleClose = (done: () => void) => {
  ElMessageBox.confirm("确定关闭弹窗嘛?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};

const formData = reactive({
  groupName: "",
  isUsed: "",
  permissionProperties: "",
  url: "",
  isUse: "1",
  publicScope: "",
  administrators: "",
  tableData: ref([
    {
      userInfo: "阿海",
      controlScope: "所有"
    }
  ])
});
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  groupName: [{ required: true, message: "请输入组名", trigger: "blur" }],
  isUsed: [{ required: true, message: "请选择是否启用", trigger: "blur" }],
  permissionProperties: [
    { required: true, message: "请选择权限属性", trigger: "blur" }
  ],
  userInfo: [
    {
      required: true,
      trigger: "blur"
    }
  ]
});
const teamTableKey = ref("");
const tableColums = [
  {
    label: "人员信息",
    prop: "userInfo",
    type: "people"
  },
  {
    label: "管控范围",
    prop: "controlScope",
    type: "department"
  },
  {
    label: "操作",
    type: "operate",
    width: 60
  },
  {
    label: "",
    type: "icon",
    width: 40
  }
];

const tableRules = reactive<FormRules>({});

function cancel() {
  this.dialogVisible = false;
}
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};

const setKey = () => {
  const date = new Date().valueOf(); // 获取时间戳
  const txt = "1234567890"; // 生成的随机机器码
  const len = 13; // 机器码有多少位
  let pwd = ""; // 定义空变量用来接收机器码
  for (let i = 0; i < len; i++) {
    pwd += txt.charAt(Math.floor(Math.random() * txt.length)); // 循环机器码位数随机填充
  }
  return date + pwd;
};

const addPerson = () => {
  formData.tableData.push({ userInfo: "", controlScope: "" });
  teamTableKey.value = setKey();
};
const deletePerson = index => {
  formData.tableData.splice(index, 1);
  teamTableKey.value = setKey();
};

//暴露出值和方法，供父组件调用
defineExpose({
  dialogVisible
});
</script>

<style scoped></style>
